import { useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { checkLoginStatus, logoutUser } from '@/store/actions/userActions';
import { isPublicRoute, requiresAuth, getRouteConfig } from '@/router/routeConfig';

/**
 * 认证Hook
 * 提供认证相关的功能和方法
 */
export const useAuth = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const dispatch = useDispatch();
  const { isLogin, loading, userInfo, token } = useSelector(state => state.user);

  // 检查登录状态
  const checkAuth = async () => {
    const localToken = localStorage.getItem('wechat_token');
    
    if (!localToken) {
      return false;
    }

    if (!isLogin) {
      const isValid = await dispatch(checkLoginStatus());
      return isValid;
    }

    return isLogin;
  };

  // 登录
  const login = (userInfo, token) => {
    localStorage.setItem('user_info', JSON.stringify(userInfo));
    localStorage.setItem('wechat_token', token);
    navigate('/home');
  };

  // 登出
  const logout = () => {
    dispatch(logoutUser());
    navigate('/login');
  };

  // 重定向到登录页
  const redirectToLogin = () => {
    navigate('/login', {
      state: { from: location.pathname }
    });
  };

  // 重定向到首页
  const redirectToHome = () => {
    navigate('/home');
  };

  // 检查是否需要重定向
  const shouldRedirect = () => {
    const currentPath = location.pathname;
    const routeConfig = getRouteConfig(currentPath);
    
    // 如果是公开页面，不需要重定向
    if (isPublicRoute(currentPath)) {
      // 如果已登录且访问登录页，重定向到首页
      if (isLogin && currentPath === '/login') {
        return '/home';
      }
      return null;
    }

    // 检查路由是否需要认证
    if (requiresAuth(currentPath) && !isLogin) {
      return '/login';
    }

    return null;
  };

  // 自动重定向
  useEffect(() => {
    const redirectPath = shouldRedirect();
    if (redirectPath) {
      navigate(redirectPath, { replace: true });
    }
  }, [isLogin, location.pathname, navigate]);

  return {
    isLogin,
    loading,
    userInfo,
    token,
    checkAuth,
    login,
    logout,
    redirectToLogin,
    redirectToHome,
    shouldRedirect
  };
};
